package com.example.PolimiAssistant;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import com.Wsdl2Code.WebServices.PolimiAssistant.CourseExam;
import com.Wsdl2Code.WebServices.PolimiAssistant.PolimiAssistant;
import com.example.PolimiAssistant.common.AlertMessage;
import com.example.PolimiAssistant.common.CommonActivity;
import com.example.PolimiAssistant.common.ExamCallAdapter;
import com.example.PolimiAssistant.common.ReminderService;
import com.example.PolimiAssistant.utils.PreferencesManager;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.Vector;

/**
 * Created by Vlado on 29.06.2014.
 */
public class ExamSchedule_detail extends CommonActivity {

    private Vector<CourseExam> examCallsCollection;
    private ExamCallAdapter listAdapter;
    private ListView examschedule_detail_calls_list;
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.exam_schedule_detail);

        examschedule_detail_calls_list = (ListView)findViewById(R.id.examschedule_detail_calls_list);

        TextView exam_schedule_detail_course_name = (TextView) findViewById(R.id.exam_schedule_detail_course_name);
        TextView exam_schedule_detail_school_name = (TextView) findViewById(R.id.exam_schedule_detail_school_name);
        TextView exam_schedule_detail_major_name = (TextView) findViewById(R.id.exam_schedule_detail_major_name);
        TextView exam_schedule_detail_sem_name = (TextView) findViewById(R.id.exam_schedule_detail_sem_name);
        TextView exam_schedule_detail_credits = (TextView) findViewById(R.id.exam_schedule_detail_credits);
        final Context context = this;
        Intent i = getIntent();
        final int course_id = i.getIntExtra("id",0);
        final String course_name = i.getStringExtra("name");
        exam_schedule_detail_course_name.setText(course_name);
        exam_schedule_detail_school_name.setText(i.getStringExtra("school_name"));
        exam_schedule_detail_major_name.setText(i.getStringExtra("major_name"));
        exam_schedule_detail_sem_name.setText(i.getStringExtra("semestar_name"));
        exam_schedule_detail_credits.setText(String.valueOf(i.getIntExtra("credits",0)));

        examschedule_detail_calls_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                CourseExam c_selected = examCallsCollection.get(position);
                try {
                    createScheduledNotification(c_selected, course_name);
                } catch (ParseException e) {
                    e.printStackTrace();
                }

                //update the list
                if (c_selected.notification_set == false) {
                    examCallsCollection.remove(position);
                    c_selected.notification_set = true;
                    examCallsCollection.add(position, c_selected);
                    listAdapter.notifyDataSetChanged();
                }
            }

        });


        new AsyncTask<Void, Void, Vector<CourseExam>>() {
            ProgressDialog loadingDialog;
            {
                loadingDialog = new ProgressDialog(ExamSchedule_detail.this);
            }
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                loadingDialog.setMessage("Loading...");
                loadingDialog.show();
            }
            @Override
            protected Vector<CourseExam> doInBackground(Void... params) {
                PolimiAssistant polimiService = new PolimiAssistant();
                PreferencesManager p = new PreferencesManager(context);
                String token = p.getToken();
                Vector<CourseExam> cList = polimiService.GetCourseExamCalls(token, course_id);

                if(cList != null && cList.size() > 0) {
                    CourseExam status = cList.get(0);
                    if (!status.valid) {
                        //TODO: signal the android that token is expiried to logout the user
                    }
                }
                if(cList == null) {
                    cList = new Vector<CourseExam>();
                    Log.e(TAG, "LOAD FAILURE: GetUserNotPassCourses RETURN NULL");
                }

                examCallsCollection = cList;
                return cList;
            }

            @Override
            protected void onPostExecute(Vector<CourseExam> list) {
                super.onPostExecute(list);
                listAdapter = new ExamCallAdapter(context,R.layout.exam_call_list_item, list);
                examschedule_detail_calls_list.setAdapter(listAdapter);
                loadingDialog.dismiss();
            }

        }.execute();
    }
    private void createScheduledNotification(CourseExam c_selected, String course_name) throws ParseException {
        // Get new calendar object and set the date to now
        Calendar calendar = Calendar.getInstance();

        SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy", Locale.US);
        Date d = sdf.parse(c_selected.stop_reg_date_str);

        calendar.setTime(d);
        calendar.add(Calendar.DATE, -2);
        calendar.set(Calendar.HOUR_OF_DAY, 12);
        calendar.set(Calendar.MINUTE, 0);
        SimpleDateFormat sdf_print = new SimpleDateFormat("dd.MM.yyyy hh:mm", Locale.US);
        String calendar_time = sdf_print.format(calendar.getTime());

        if(c_selected.notification_set)
        {
            AlertMessage am = new AlertMessage(context,"The notification is already beeing set for " + calendar_time);
            am.Show();
        }
        else if(calendar.getTimeInMillis() < Calendar.getInstance().getTimeInMillis())
        {
            c_selected.notification_set = true;
            AlertMessage am = new AlertMessage(context,"The registration for the exam is closed");
            am.Show();
        }
        else
        {
            // Retrieve alarm manager from the system
            AlarmManager alarmManager = (AlarmManager) getApplicationContext().getSystemService(getBaseContext().ALARM_SERVICE);
            // Every scheduled intent needs a different ID, else it is just executed once
            int id = c_selected.id;//its unique for that call

            //save in the db
            PushNotification(c_selected);
            // Prepare the intent which should be launched at the date
            Intent intent = new Intent(this, ReminderService.class);
            intent.putExtra("course_exam_id", c_selected.id);
            intent.putExtra("course_exam_start_reg", c_selected.strat_reg_date_str);
            intent.putExtra("course_exam_stop_reg", c_selected.stop_reg_date_str);
            intent.putExtra("course_exam_date", c_selected.exam_datetime_str);
            intent.putExtra("course_exam_name", course_name);
            intent.putExtra("course_exam_classroom", c_selected.classroom_nameField);

            Log.d("POLIWS", "alarm set for " + course_name + " at " + calendar_time);

            // Prepare the pending intent
            PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), id, intent, PendingIntent.FLAG_UPDATE_CURRENT);


            // Register the alert in the system. You have the option to define if the device has to wake up on the alert or not
            alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);

            AlertMessage am = new AlertMessage(context,"The notification beeing set for " + calendar_time);
            am.Show();
        }
    }

    private void PushNotification(final CourseExam c_exam){
        final AsyncTask<Void, Void, Void> execute = new AsyncTask<Void, Void, Void>() {
            ProgressDialog loadingDialog;

            {
                loadingDialog = new ProgressDialog(ExamSchedule_detail.this);
            }
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                loadingDialog.setMessage("Loading...");
                loadingDialog.show();
            }
            @Override
            protected Void doInBackground(Void... params) {
                PolimiAssistant polimiService = new PolimiAssistant();
                PreferencesManager p = new PreferencesManager(context);
                String token = p.getToken();
                polimiService.PushUserNotification(token, c_exam.id);
                return null;
            }
            @Override
            protected void onPostExecute(Void rez) {
                super.onPostExecute(rez);
                loadingDialog.dismiss();
            }

        }.execute();
    }
}